const request = require("request");
const express = require("express");
const jwt = require("jsonwebtoken");
const User = require("./model/user.js");
const Banner = require("./model/banner.js");
const Article = require("./model/article.js");
const Interview = require("./model/interview.js");
const Lesson = require("./model/lesson.js");
const app = express();
const multer = require("multer");
const OSS = require("ali-oss");
app.use(express.static(__dirname));

const client = new OSS({
  region: "oss-cn-beijing",
  accessKeyId: "LTAI5t8xMijXjetrUg6jBhxP",
  accessKeySecret: "SHx2e58MgTiXhKvivowcGxIs2fJlkk",
  bucket: "zishui",
});

const upload = multer({
  dest: "uploads/",
});
// 用于生成Token的密钥
const secretKey = "jw-token";

function verifyToken(req, res, next) {
  // 从请求头中获取 Authorization 字段的值
  const authHeader = req.headers["authorization"];
  const token = authHeader && authHeader.split(" ")[1];
  if (token == null) {
    // 如果请求头中没有 Authorization 字段或者 token 不存在，则返回 401 Unauthorized 响应
    return res.sendStatus(401);
  }
  jwt.verify(token, secretKey, (err, decoded) => {
    if (err) {
      return res.sendStatus(403);
    }
    // 将解码后的 token 保存到请求对象中，以便后续的路由处理函数使用
    req.openid = decoded.openid;
    next();
  });
}

app.get("/login", (req, res) => {
  const code = req.query.code;
  const appid = "wx2ad70a9c3b41c9a5"; // 修改成自己的appid，secret
  const secret = "59bf0ac46b95834ce52275eb1a06ed3d";
  const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`;

  request.get(url, async (error, response, body) => {
    if (!error && response.statusCode == 200) {
      const data = JSON.parse(body);
      const openid = data.openid;
      const token = jwt.sign({ openid }, secretKey);
      // 这里可以通过openid 查看用户是否注册，如果注册过查询昵称和头像
      let user = await User.findOne({ openid });
      if (!user) {
        user = await User.create({ openid }); // 没有注册过就注册一个
      }
      res.json({
        error: 0,
        data: {
          token,
          nickname: user.nickname,
          avatar: user.avatar,
        },
      });
    } else {
      res.json({
        error: 1,
        message: "获取失败openid失败",
      });
    }
  });
});

app.post("/upload", verifyToken, upload.single("avatar"), async (req, res) => {
  const openid = req.openid;
  const file = req.file;
  const filePath = file.path;
  const key = "images/" + file.filename;
  const { url: avatar } = await client.put(key, filePath);
  const nickname = req.body.nickname;
  await User.findOneAndUpdate(
    { openid },
    {
      nickname,
      avatar,
    }
  );
  res.json({
    error: 0,
    nickname,
    avatar,
  });
});
// banner接口
app.get("/bannerList", async (req, res) => {
  let bannerList = await Banner.find({});
  res.json({
    error: 0,
    bannerList,
  });
});
app.get("/articleList", async function (req, res) {
  const page = parseInt(req.query.page) || 1; // 默认为第一页
  const limit = parseInt(req.query.limit) || 10;
  const skip = (page - 1) * limit;
  const [articles, total] = await Promise.all([
    Article.find().skip(skip).limit(limit),
    Article.countDocuments(),
  ]);
  // await new Promise((resolve, reject) => setTimeout(() => { resolve() }, 1000))
  res.json({
    error: 0,
    articles,
    total,
  });
});
app.get("/article", async function (req, res) {
  const id = req.query.id; // 默认为第一页
  let article = await Article.findById(id);
  res.json({
    error: 0,
    article,
  });
});
app.get("/interview", async function (req, res) {
  const type = req.query.type; // 默认为第一页
  let interview = await Interview.find({ type });
  res.json({
    error: 0,
    interview,
  });
});
app.get("/lesson", async function (req, res) {
  let lesson = await Lesson.find({});
  res.json({
    error: 0,
    lesson,
  });
});
app.listen(3000, function () {
  console.log("server start 3000");
});
